<template>
  <div class="dialog_import">
    <el-form :model="{}" size="medium" :inline="true" label-width="60px">
      <el-form-item label="操作栏" prop="" v-hasPermi="['manage_basevalue_add']">
        <el-button type="primary" plain icon="el-icon-plus" size="medium" @click="handleAdd">添加巡检计划</el-button>
      </el-form-item>
      <!-- <el-form-item label="" prop="">
        <el-button type="primary" @click="() => dialogTableVisible = true" plain icon="el-icon-upload2" size="medium">
          导入基值列表</el-button>
      </el-form-item> -->
      <el-dialog title="导入基值列表详情" :visible.sync="dialogTableVisible" width="70%">
        <el-button style="float: left;margin-right: 20px;" type="primary" @click="logload" plain icon="el-icon-download"
          size="medium">
          下载基值列表模板</el-button>
        <el-upload :action="uploadFileUrl" :multiple="false" :show-file-list="false" :headers="headers"
          accept=".xlsx,csv,application/vnd.ms-excel,applications/vnd.openxmlforms-officedocument.spreadsheetml.sheet"
          :http-request="httpRequest">
          <el-button type="primary" plain icon="el-icon-upload2" size="medium">上传文件</el-button>
        </el-upload>
        <h4>解析结果：</h4>
        <div class="file_div">
          <el-scrollbar style="width:100%;height:300px;">
            <el-table :data="tableData" :loading="loading">
              <el-table-column prop="设备名称" label="设备名称" min-width="160" show-overflow-tooltip></el-table-column>
              <el-table-column prop="品牌" label="品牌" min-width="160" show-overflow-tooltip></el-table-column>
              <el-table-column prop="规格型号" label="规格型号" min-width="160" show-overflow-tooltip></el-table-column>
              <el-table-column prop="供应商名称" label="供应商名称" min-width="180" show-overflow-tooltip></el-table-column>
              <el-table-column prop="类别名称" label="类别名称" min-width="160" show-overflow-tooltip></el-table-column>
              <el-table-column prop="单位名称" label="单位名称" min-width="160" show-overflow-tooltip></el-table-column>
              <el-table-column prop="计量设备" label="计量设备" min-width="160" show-overflow-tooltip></el-table-column>
              <el-table-column prop="计量编号" label="计量编号" min-width="130" show-overflow-tooltip></el-table-column>
              <el-table-column prop="备注" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
              <!-- <el-table-column label="操作" width="130" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button icon="el-icon-delete" size="small" type="danger" @click="handleDelete(scope.$index)">删除
              </el-button>
            </template>
          </el-table-column> -->
            </el-table>
          </el-scrollbar>
        </div>

        <div align="center" slot="footer" class="dialog-footer">
          <el-button type="primary" :loading="btnloading" @click="submitForm">导入</el-button>
          <el-button @click="() => dialogTableVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </el-form>
    <template v-if="open">
      <addbaseValue :title="title"></addbaseValue>
    </template>
  </div>
</template>

<script>
// import XLSX from 'xlsx'
import { importEquipmentBaseTemplate, importEquipmentBaseExcel } from '@/api/equipment/equipment.js'
import { getToken } from "@/utils/auth";
const XLSX = require('xlsx');
export default {
  name: 'manage',
  components: {
    addbaseValue: () => import('../form/addbaseValue.vue')
  },
  data () {
    return {
      title: '添加巡检计划',
      open: false,
      dialogTableVisible: false,
      tableData: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      loading: false,
      btnloading: false,
      fileList: {}
    }
  },
  watch: {
    dialogTableVisible (val) {
      if (!val) {
        this.tableData = []
      }
    }
  },
  methods: {
    /**
     * 创建下载链接
     */
    logload () {
      let data = {};
      let filename = '设备基值列表模板.xlsx';
      importEquipmentBaseTemplate(data, filename).then()
      // dom中创建a标签
      // let aTag = document.createElement('a')
      // // 给创建的a标签添加href属性并赋值
      // aTag.href = `http://139.159.212.47:9310/statics/2022/08/29/a306372d-67c6-4bb8-afb5-d04d228f3a21.xlsx`

      // aTag.download = '设备基值列表.xlsx'
      // 自动点击创建的标签
      // aTag.click()

      // 不再使用时需释放createObjectURL创建得对象
      // URL.revokeObjectURL(blob)
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.$emit('selectList')
    },
    handleDelete (index) {
      this.tableData.splice(index, 1)
    },
    submitForm () {
      if (this.tableData.length === 0) return this.$message.error('请选择导入文件')
      this.btnloading = true
      console.log(this.fileList);
      let formData = new FormData();
      formData.append('file', this.fileList)
      console.log(formData);
      importEquipmentBaseExcel(formData).then((res) => {
        this.$message.success('操作成功')
        this.btnloading = false
        this.dialogTableVisible = false
        this.$emit('selectList')
      }).catch(() => {
        this.btnloading = false
      })
    },
    /** 导入解析json格式 */
    httpRequest (e) {
      let file = e.file
      console.log('e', e);
      console.log('file', e.file);
      this.fileList = e.file
      this.loading = true
      if (!file) {
        //没有文件
        this.loading = false
        return false
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        //格式根据自己需求定义
        this.loading = false
        return this.$message.error('格式上传不正确,请上传xls,xlsx')
      }
      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          // console.log(XLSX);
          const data = ev.target.result
          const workbook = XLSX.read(data, { type: 'binary' })//字符编码解析
          const exlname = workbook.SheetNames[0]//取第一张表
          const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname])//生成json表格内容
          console.log(exl);
          this.tableData = exl
          this.loading = false
          document.getElementsByName('file')[0].value = ''
        } catch (error) {
          console.log('出错了', error);
          this.loading = false
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    }
  }
}
</script>

<style lang="scss" scoped>
.file_div {
  overflow: hidden;
  border: 1px solid #999;
  border-radius: 10px;
}

::v-deep.dialog_import .el-scrollbar__wrap {
  overflow-x: hidden !important;
}
</style>